import sendRequest from "../utils/request";

import {
  cbdIsLogin,
  cbdLogin,
  cbdGetMemberId,
  wxGetSessionCode,
  wxIsLogin,
  wxLogin
} from "../utils/login";
import { getEnv } from "../utils/util";

const requestFlex = sendRequest;

const request = async paramsOuter => {
  let env = await getEnv();

  const { needLogin = false, config, url, params } = paramsOuter;

  if (!needLogin) return sendRequest(url, params, config);
  else {
    // 判断登录
    // 登录过 拿memberId
    // 没有登录 去登陆
    // let param;

    if (env == "cbd") {
      let res = await cbdIsLogin();
      if (!res) {
        await cbdLogin();
        return Promise.reject(false);
      }
      let memberId = await cbdGetMemberId();
      // let memberId =
      // "76d0c3abf0d347f2b91423b8523392c8" || (await cbdGetMemberId());
      params.data = { ...params.data, memberId };
    } else if (env == "mini") {
      console.log(location.href);
      let isWxLogin = await wxIsLogin();
      if (!isWxLogin) {
        wxLogin();
        return Promise.reject(false);
      }

      // TODO: undo this
      let sessionCode = await wxGetSessionCode();
      // let sessionCode =
      //   "d22c60f65e7eaf6907804eb4e23d3f74f0783698a75dc7e0d5f9f1b5b6fccd414440482049170c1aaff9b9f612c79edf";

      params.data = { sessionCode, ...params.data };
    }
    // else if (env == "h5") {
    //   let memberId = "76d0c3abf0d347f2b91423b8523392c8";
    //   params.data = { ...params.data, memberId };
    // }

    return requestFlex(url, params, config);
  }
};

export default request;
